<template>
  <div class="admin-resources">
    <el-card class="resources-card">
      <template #header>
        <div class="card-header">
          <h3>课件资源管理</h3>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索资源"
              class="search-input"
              prefix-icon="el-icon-search"
              clearable
              @clear="handleSearch"
              @input="handleSearch"
            />
            <el-button type="primary" @click="handleExportResources">导出资源</el-button>
          </div>
        </div>
      </template>

      <!-- 资源类型切换 -->
      <el-tabs v-model="activeTab" @tab-click="handleTabChange">
        <el-tab-pane label="全部资源" name="all"></el-tab-pane>
        <el-tab-pane label="课件" name="courseware"></el-tab-pane>
        <el-tab-pane label="习题" name="exercises"></el-tab-pane>
        <el-tab-pane label="视频" name="video"></el-tab-pane>
        <el-tab-pane label="音频" name="audio"></el-tab-pane>
        <el-tab-pane label="图片" name="image"></el-tab-pane>
      </el-tabs>

      <!-- 筛选条件 -->
      <div class="filter-container">
        <div class="filter-item">
          <span class="filter-label">学科：</span>
          <el-select v-model="filters.subject" placeholder="选择学科" clearable @change="handleFilterChange">
            <el-option v-for="item in subjectOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
        <div class="filter-item">
          <span class="filter-label">创建时间：</span>
          <el-date-picker
            v-model="filters.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleFilterChange"
          />
        </div>
        <div class="filter-item">
          <span class="filter-label">创建者：</span>
          <el-select v-model="filters.creator" placeholder="选择创建者" clearable @change="handleFilterChange">
            <el-option v-for="item in creatorOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
      </div>

      <!-- 资源列表表格 -->
      <el-table :data="filteredResources" style="width: 100%" v-loading="loading">
        <el-table-column label="ID" prop="id" width="80" />
        <el-table-column label="资源名称" prop="name" min-width="180">
          <template #default="scope">
            <el-link type="primary" @click="handlePreview(scope.row)">{{ scope.row.name }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getResourceTagType(scope.row.type)">
              {{ getResourceTypeName(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="学科" prop="subject" width="100" />
        <el-table-column label="文件大小" prop="size" width="100">
          <template #default="scope">
            {{ formatFileSize(scope.row.size) }}
          </template>
        </el-table-column>
        <el-table-column label="创建者" prop="creator" width="120" />
        <el-table-column label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button type="text" size="small" @click="handlePreview(scope.row)">预览</el-button>
            <el-button type="text" size="small" @click="handleDownload(scope.row)">下载</el-button>
            <el-button type="text" size="small" class="danger-text" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 资源导出对话框 -->
    <el-dialog title="导出资源" v-model="exportDialogVisible" width="500px">
      <el-form :model="exportForm" label-width="100px">
        <el-form-item label="资源类型">
          <el-checkbox-group v-model="exportForm.types">
            <el-checkbox label="courseware">课件</el-checkbox>
            <el-checkbox label="exercises">习题</el-checkbox>
            <el-checkbox label="video">视频</el-checkbox>
            <el-checkbox label="audio">音频</el-checkbox>
            <el-checkbox label="image">图片</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="学科">
          <el-select v-model="exportForm.subject" placeholder="选择学科" clearable style="width: 100%">
            <el-option v-for="item in subjectOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="exportForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="导出格式">
          <el-radio-group v-model="exportForm.format">
            <el-radio label="zip">ZIP压缩包</el-radio>
            <el-radio label="excel">Excel表格</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="exportDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmExport">确认导出</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog title="资源预览" v-model="previewDialogVisible" width="70%">
      <div class="preview-container" v-if="previewResource">
        <template v-if="previewResource.type === 'courseware'">
          <iframe :src="previewResource.url" class="preview-iframe"></iframe>
        </template>
        <template v-else-if="previewResource.type === 'exercises'">
          <div class="exercises-preview">
            <h4>{{ previewResource.name }}</h4>
            <div v-html="previewResource.content"></div>
          </div>
        </template>
        <template v-else-if="previewResource.type === 'video'">
          <video controls class="preview-video">
            <source :src="previewResource.url" type="video/mp4">
            您的浏览器不支持视频播放
          </video>
        </template>
        <template v-else-if="previewResource.type === 'audio'">
          <audio controls class="preview-audio">
            <source :src="previewResource.url" type="audio/mpeg">
            您的浏览器不支持音频播放
          </audio>
        </template>
        <template v-else-if="previewResource.type === 'image'">
          <img :src="previewResource.url" class="preview-image" />
        </template>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="previewDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleDownload(previewResource)">下载</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 数据加载状态
const loading = ref(false);

// 资源列表数据
const resourceList = ref([]);
const filteredResources = ref([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const totalCount = ref(0);

// 搜索关键词
const searchKeyword = ref('');

// 当前选中的标签页
const activeTab = ref('all');

// 筛选条件
const filters = reactive({
  subject: '',
  dateRange: [],
  creator: ''
});

// 导出对话框
const exportDialogVisible = ref(false);
const exportForm = reactive({
  types: ['courseware', 'exercises'],
  subject: '',
  dateRange: [],
  format: 'zip'
});

// 预览对话框
const previewDialogVisible = ref(false);
const previewResource = ref(null);

// 学科选项
const subjectOptions = [
  { value: '数学', label: '数学' },
  { value: '语文', label: '语文' },
  { value: '英语', label: '英语' },
  { value: '物理', label: '物理' },
  { value: '化学', label: '化学' },
  { value: '生物', label: '生物' },
  { value: '历史', label: '历史' },
  { value: '地理', label: '地理' },
  { value: '政治', label: '政治' }
];

// 创建者选项
const creatorOptions = [
  { value: '张老师', label: '张老师' },
  { value: '李老师', label: '李老师' },
  { value: '王老师', label: '王老师' },
  { value: '陈老师', label: '陈老师' },
  { value: '赵老师', label: '赵老师' }
];

// 初始化
onMounted(() => {
  loadResourceData();
});

// 加载资源数据
const loadResourceData = async () => {
  loading.value = true;
  try {
    // 这里应该调用API获取资源数据
    // 以下是模拟数据
    setTimeout(() => {
      const mockData = [];
      // 生成课件资源
      for (let i = 1; i <= 30; i++) {
        const subject = subjectOptions[Math.floor(Math.random() * subjectOptions.length)].value;
        const creator = creatorOptions[Math.floor(Math.random() * creatorOptions.length)].value;
        mockData.push({
          id: 1000 + i,
          name: `${subject}课件-${i}`,
          type: 'courseware',
          subject: subject,
          size: Math.floor(Math.random() * 10000000),
          creator: creator,
          createTime: new Date(2023, Math.floor(Math.random() * 6), Math.floor(Math.random() * 28) + 1).getTime(),
          url: '#',
          content: null
        });
      }
      // 生成习题资源
      for (let i = 1; i <= 25; i++) {
        const subject = subjectOptions[Math.floor(Math.random() * subjectOptions.length)].value;
        const creator = creatorOptions[Math.floor(Math.random() * creatorOptions.length)].value;
        mockData.push({
          id: 2000 + i,
          name: `${subject}习题-${i}`,
          type: 'exercises',
          subject: subject,
          size: Math.floor(Math.random() * 1000000),
          creator: creator,
          createTime: new Date(2023, Math.floor(Math.random() * 6), Math.floor(Math.random() * 28) + 1).getTime(),
          url: '#',
          content: `<div>
            <p>1. 这是${subject}习题的第一题</p>
            <p>2. 这是${subject}习题的第二题</p>
            <p>3. 这是${subject}习题的第三题</p>
          </div>`
        });
      }
      // 生成视频资源
      for (let i = 1; i <= 15; i++) {
        const subject = subjectOptions[Math.floor(Math.random() * subjectOptions.length)].value;
        const creator = creatorOptions[Math.floor(Math.random() * creatorOptions.length)].value;
        mockData.push({
          id: 3000 + i,
          name: `${subject}教学视频-${i}`,
          type: 'video',
          subject: subject,
          size: Math.floor(Math.random() * 100000000),
          creator: creator,
          createTime: new Date(2023, Math.floor(Math.random() * 6), Math.floor(Math.random() * 28) + 1).getTime(),
          url: '#',
          content: null
        });
      }
      // 生成音频资源
      for (let i = 1; i <= 10; i++) {
        const subject = subjectOptions[Math.floor(Math.random() * subjectOptions.length)].value;
        const creator = creatorOptions[Math.floor(Math.random() * creatorOptions.length)].value;
        mockData.push({
          id: 4000 + i,
          name: `${subject}教学音频-${i}`,
          type: 'audio',
          subject: subject,
          size: Math.floor(Math.random() * 50000000),
          creator: creator,
          createTime: new Date(2023, Math.floor(Math.random() * 6), Math.floor(Math.random() * 28) + 1).getTime(),
          url: '#',
          content: null
        });
      }
      // 生成图片资源
      for (let i = 1; i <= 20; i++) {
        const subject = subjectOptions[Math.floor(Math.random() * subjectOptions.length)].value;
        const creator = creatorOptions[Math.floor(Math.random() * creatorOptions.length)].value;
        mockData.push({
          id: 5000 + i,
          name: `${subject}教学图片-${i}`,
          type: 'image',
          subject: subject,
          size: Math.floor(Math.random() * 5000000),
          creator: creator,
          createTime: new Date(2023, Math.floor(Math.random() * 6), Math.floor(Math.random() * 28) + 1).getTime(),
          url: '#',
          content: null
        });
      }
      
      resourceList.value = mockData;
      filterResources();
      loading.value = false;
    }, 500);
  } catch (error) {
    console.error('加载资源数据失败', error);
    ElMessage.error('加载资源数据失败');
    loading.value = false;
  }
};

// 筛选资源
const filterResources = () => {
  let filtered = [...resourceList.value];
  
  // 根据标签页筛选
  if (activeTab.value !== 'all') {
    filtered = filtered.filter(resource => resource.type === activeTab.value);
  }
  
  // 应用学科筛选
  if (filters.subject) {
    filtered = filtered.filter(resource => resource.subject === filters.subject);
  }
  
  // 应用日期范围筛选
  if (filters.dateRange && filters.dateRange.length === 2) {
    const startTime = filters.dateRange[0].getTime();
    const endTime = filters.dateRange[1].getTime();
    filtered = filtered.filter(resource => {
      return resource.createTime >= startTime && resource.createTime <= endTime;
    });
  }
  
  // 应用创建者筛选
  if (filters.creator) {
    filtered = filtered.filter(resource => resource.creator === filters.creator);
  }
  
  // 应用搜索关键词
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.toLowerCase();
    filtered = filtered.filter(resource => 
      resource.name.toLowerCase().includes(keyword) || 
      resource.subject.toLowerCase().includes(keyword) || 
      resource.creator.toLowerCase().includes(keyword)
    );
  }
  
  // 计算总数
  totalCount.value = filtered.length;
  
  // 应用分页
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  filteredResources.value = filtered.slice(start, end);
};

// 处理标签页变化
const handleTabChange = () => {
  currentPage.value = 1;
  filterResources();
};

// 处理筛选条件变化
const handleFilterChange = () => {
  currentPage.value = 1;
  filterResources();
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  filterResources();
};

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  filterResources();
};

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  filterResources();
};

// 获取资源类型名称
const getResourceTypeName = (type) => {
  const typeMap = {
    'courseware': '课件',
    'exercises': '习题',
    'video': '视频',
    'audio': '音频',
    'image': '图片'
  };
  return typeMap[type] || '未知';
};

// 获取资源类型标签类型
const getResourceTagType = (type) => {
  const typeMap = {
    'courseware': 'primary',
    'exercises': 'success',
    'video': 'danger',
    'audio': 'warning',
    'image': 'info'
  };
  return typeMap[type] || 'info';
};

// 格式化日期
const formatDate = (timestamp) => {
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 处理预览资源
const handlePreview = (resource) => {
  previewResource.value = resource;
  previewDialogVisible.value = true;
};

// 处理下载资源
const handleDownload = (resource) => {
  // 这里应该调用API下载资源
  // 以下是模拟操作
  ElMessage.success(`开始下载：${resource.name}`);
};

// 处理删除资源
const handleDelete = (resource) => {
  ElMessageBox.confirm(`确定要删除资源 ${resource.name} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用API删除资源
    // 以下是模拟操作
    const index = resourceList.value.findIndex(item => item.id === resource.id);
    if (index !== -1) {
      resourceList.value.splice(index, 1);
      filterResources();
      ElMessage.success('删除成功');
    }
  }).catch(() => {});
};

// 处理导出资源
const handleExportResources = () => {
  // 重置导出表单
  exportForm.types = ['courseware', 'exercises'];
  exportForm.subject = filters.subject;
  exportForm.dateRange = filters.dateRange;
  exportForm.format = 'zip';
  
  exportDialogVisible.value = true;
};

// 确认导出
const confirmExport = () => {
  // 这里应该调用API导出资源
  // 以下是模拟操作
  const typeNames = exportForm.types.map(type => getResourceTypeName(type)).join('、');
  const subjectName = exportForm.subject ? `学科：${exportForm.subject}` : '全部学科';
  const formatName = exportForm.format === 'zip' ? 'ZIP压缩包' : 'Excel表格';
  
  ElMessage.success(`开始导出 ${typeNames} (${subjectName}) 的资源，格式：${formatName}`);
  exportDialogVisible.value = false;
};
</script>

<style scoped>
.admin-resources {
  padding: 20px;
}

.resources-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.search-input {
  width: 250px;
}

.filter-container {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20px;
  gap: 15px;
}

.filter-item {
  display: flex;
  align-items: center;
}

.filter-label {
  margin-right: 5px;
  white-space: nowrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.danger-text {
  color: #F56C6C;
}

.danger-text:hover {
  color: #f78989;
}

.preview-container {
  min-height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.preview-iframe {
  width: 100%;
  height: 600px;
  border: none;
}

.exercises-preview {
  width: 100%;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.preview-video, .preview-audio {
  width: 100%;
  max-height: 500px;
}

.preview-image {
  max-width: 100%;
  max-height: 500px;
}
</style> 